﻿using Microsoft.Win32;
using System;
using System.Windows;

namespace StartTool
{
    public partial class App : Application
    {
        private static System.Threading.Mutex IMutex;
        protected override void OnStartup(StartupEventArgs e)
        {
            SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
            string MyAppID = "OnlyRun_Client";//运行进程互斥标识名称 可自行修改
            IMutex = new System.Threading.Mutex(true, MyAppID);
            if (IMutex.WaitOne(0, false))
            {
                ///正常启动程序
                base.OnStartup(e);
            }
            else
            {
                MessageBox.Show("程序已经在运行！", "提示", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                this.Shutdown();//已存在运行进程 执行关闭
            }
        }

        void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
        {
            var session = e.Reason;
            switch (session)
            {
                //用户登录
                case SessionSwitchReason.SessionLogon:
                    ExecSession("用户登录");
                    break;
                //解锁屏
                case SessionSwitchReason.SessionUnlock:
                    ExecSession("解锁屏");
                    break;
                //锁屏
                case SessionSwitchReason.SessionLock:
                    BeginSessionLock();
                    break;
                //注销
                case SessionSwitchReason.SessionLogoff:
                    ExecSession("注销");
                    break;
            }
        }

        private void ExecSession(string msg)
        {
            Console.WriteLine("===>" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "  " + msg + "\n");
            CommonLog.LogWrite(msg);
        }

        /// <summary>
        /// 锁屏后执行
        /// </summary>
        private void BeginSessionLock()
        {
            ExecSession("锁屏后执行\n");
            string isopen = Config.ReadIni("EnableOpen", "IsOpen", null);
            if(isopen == "1")
            {
                Common.RunCmd("taskkill  /F /IM wechat.exe");
                ExecSession("执行完成\n");
            }
            
        }
    }
}
